<?php
import('ORG.Net.UploadFile');
import('@.ORG.Util.Image');
define('TYPE_IMAGE', 'image');
define('TYPE_VIDEO', 'video');
define('OSSURL','http://oss.mboxone.com/');
include("ueditor/oss_sdk/sdk.class.php");
/*
 * 调用插件资源的Action
 *
 */
class UploadAction extends Action {
	
	private $bucket='miyouquan';
    private $endpoint="http://oss-cn-beijing.aliyuncs.com";
    public function __construct($fileField, $config, $type = "upload")
    {
        $this->oss = new ALIOSS();
        $this->oss->set_debug_mode(true);
    }
    public function upload() {
        if (!empty($_FILES)) {
            $this->_upload();
        }
    }
    
    public function uploadtocustomer() {
    	$retVal = Session::init();
    	if (!$retVal) {
    		echo json_encode(array(
    				"failure" => true,
    				"error" => "参数错误，无法上传文件"));
    		return;
    	}
    	 
    	$customerId = Session::$user['customerId'];
    	if (!empty($_FILES)) {
    		$savePath = UPLOAD_BASE_PATH . $customerId . DIRECTORY_SEPARATOR;
    		if (!file_exists($savePath)) {
    			$e = mkdir($savePath);
    			if(!$e){
    				Log::write('mkdir err' . $savePath);
    				echo json_encode(array(
    						"failure" => true,
    						"error" => "系统错误，无法上传文件"));
    				return;
    			}
    		}
    		$remotePath = UPLOAD_REMOTE_PATH . $customerId . '/';
    		$this->_uploadWithThumb($savePath, $remotePath);
    	}
    }
    
    public function uploadtowsq() {
    	$retVal = Session::init();
    	if (!$retVal) {
    		echo json_encode(array(
    			"failure" => true,
    			"error" => "参数错误，无法上传文件"));
    			return;
    	}
    	
    	$customerId = Session::$user['customerId'];
    	if (!empty($_FILES)) {
    		$savePath = WSQ_PIC_PATH . $customerId . DIRECTORY_SEPARATOR;
    		if (!file_exists(WSQ_PIC_PATH)) {
    			$e = mkdir(WSQ_PIC_PATH);
    			if(!$e){
    				Log::write('mkdir err' . WSQ_PIC_PATH);
    				echo json_encode(array(
    						"failure" => true,
    						"error" => "系统错误，无法上传文件"));
    				return;
    			}
    		}
    		if (!file_exists($savePath)) {
    			$e = mkdir($savePath);
    			if(!$e){
    				Log::write('mkdir err' . $savePath);
    				echo json_encode(array(
    						"failure" => true,
    						"error" => "系统错误，无法上传文件"));
    				return;
    			}
    		}
    		
    		$remotePath = WSQ_PIC_REMOTE_PATH . $customerId . '/';
    		
    		$type = $_GET["type"];
    		if (!isset($type)) {
    			$type = TYPE_IMAGE;
    		}
    		if ($type == TYPE_IMAGE) {
	     		$this->_uploadWithThumb($savePath, $remotePath);
    		} else if ($type == TYPE_VIDEO) {
    			$this->_uploadVideo($savePath, $remotePath);
    		} else {
    			echo json_encode(array(
    					"failure" => true,
    					"error" => "参数错误，上传类型错误"));
    		}
    	}
    }
    
    protected  function _uploadVideo($savePath, $remotePath) {
    	//导入上传类
    	$upload = new UploadFile();
    	//设置上传文件大小
    	//1024*1024*2
    	$upload->maxSize            = 1024 * 1024 * 20;//20M
    	//设置上传文件类型
    	$upload->allowExts          = explode(',', 'mpg,mpeg,mp4');
    	//设置附件上传目录
    	$upload->savePath           =  $savePath;
    	//设置上传文件规则
    	$upload->saveRule           = 'uniqid';
    	 
    	$pathinfo = pathinfo($_FILES[0]['name']);
    	$ext =  $pathinfo['extension'];
    	if (!$upload->upload()) {
    		//捕获上传异常
    		echo json_encode(array(
    				"failure" => true,
    				"error" => strval($upload->getErrorMsg())
    		));
    	} else {
    		//取得成功上传的文件信息
    		$uploadList = $upload->getUploadFileInfo();
    		 
    		//给m_缩略图添加水印, Image::water('原文件名','水印图片地址')
    		//Image::water($uploadList[0]['savepath'] . 'm_' . $uploadList[0]['savename'], APP_PATH.'Tpl/Public/Images/logo.png');
    		 
    		$_POST['image'] = $uploadList[0]['savename'];
    		if ($_POST['image'] ) {
    			$remoteFileName = C("SERVER_HOST") . $remotePath . $uploadList[0]['savename'];
//     			$localFileName = 
//     			$posterName =  $savePath . $uploadList[0]['savename'] . '.jpg'; 
//     			$ogmName =   $savePath . $uploadList[0]['savename'] . '.ogm';
//     			$this->flv_convert_get_thumb($fileName, $posterName, $ogmName);

    			$posterName  = 'http://www.happyidea.com.cn/resource/wx_video/none.jpg';
    			echo json_encode(array(
    					"success" => true,
    					"fileName" =>  $remoteFileName,
    					"posterName" => $posterName
    			));
    		} else {
    		}
    	}
    }
    
    protected function _uploadWithThumb($savePath, $remotePath) {
    	//导入上传类
    	$upload = new UploadFile();
    	//设置上传文件大小
    	//1024*1024*2
    	$upload->maxSize            = 1024 * 1024 * 2;//2M
    	//设置上传文件类型
    	$upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
    	//设置需要生成缩略图，仅对图像文件有效
    	$upload->thumb = true;
    	//设置需要生成缩略图的文件后缀
    	$upload->thumbPrefix 		= 'm_,s_';  //生产2张缩略图
    	//设置缩略图最大宽度
    	$upload->thumbMaxWidth 		= '960,150';
    	//设置缩略图最大高度
    	$upload->thumbMaxHeight 	= '960,150';
    	//设置附件上传目录
    	$upload->savePath           =  $savePath;
    	//设置上传文件规则
    	$upload->saveRule           = 'uniqid';
    	
    	if (!$upload->upload()) {
    		//捕获上传异常
    		echo json_encode(array(
    				"failure" => true,
    				"error" => strval($upload->getErrorMsg())
    		));
    	} else {
    		//取得成功上传的文件信息
    		$uploadList = $upload->getUploadFileInfo();
    		 
    		//给m_缩略图添加水印, Image::water('原文件名','水印图片地址')
    		//Image::water($uploadList[0]['savepath'] . 'm_' . $uploadList[0]['savename'], APP_PATH.'Tpl/Public/Images/logo.png');
    		 
    		$_POST['image'] = $uploadList[0]['savename'];
    		if ($_POST['image'] ) {
    			$fileName = C("SERVER_HOST") . $remotePath . $uploadList[0]['savename'];
    			echo json_encode(array(
    					"success" => true,
    					"fileName" =>  $fileName
    			));
    		} else {
    		}
    	}
    }
	
    // 图片文件上传
    protected function _upload($savePath = UPLOAD_BASE_PATH) {
    	//导入上传类
    	$upload = new UploadFile();
    	//设置上传文件大小
    	//1024*1024*2
    	$upload->maxSize            = 1024 * 1024 * 2;//2M
    	//设置上传文件类型
    	$upload->allowExts          = explode(',', 'jpg,gif,png,jpeg,xls,xlsx');
    	//设置附件上传目录
    	$upload->savePath           =  $savePath;
    	//设置上传文件规则
    	$upload->saveRule           = 'uniqid';
    	
    	if (!$upload->upload()) {
    		//捕获上传异常
    		echo json_encode(array(
    				"failure" => true,
    				"error" => strval($upload->getErrorMsg())
    		));
    	} else {
    		//取得成功上传的文件信息
    		$uploadList = $upload->getUploadFileInfo();
    		
    		//给m_缩略图添加水印, Image::water('原文件名','水印图片地址')
    		//Image::water($uploadList[0]['savepath'] . 'm_' . $uploadList[0]['savename'], APP_PATH.'Tpl/Public/Images/logo.png');
    		
    		$_POST['image'] = $uploadList[0]['savename'];
    		if ($_POST['image'] ) {
    			echo json_encode(array(
    					"success" => true,
    					"fileName" => $uploadList[0]['savename']
    			));
    		} else {
    		}
    	}
    }
    
    /**
     * 
     * 删除./Uploads/路径下的指定文件
     * @param unknown_type $fileName
     * @param unknown_type $prefix1
     * @param unknown_type $prefix2
     * @param unknown_type $prefix3
     */
    public function deleteFile($fileName,$prefix1=null,$prefix2=null,$prefix3=null) {
    	if(file_exists(UPLOAD_BASE_PATH . $fileName)){
    		if (isset($prefix1)) {
	    		if(file_exists(UPLOAD_BASE_PATH . $prefix1. $fileName)){
	    			unlink(UPLOAD_BASE_PATH .$prefix1. $fileName);
	    		}
    		}
    		if (isset($prefix2)) {
	    		if(file_exists(UPLOAD_BASE_PATH . $prefix2.$fileName)){
	    			unlink(UPLOAD_BASE_PATH . $prefix2.$fileName);
	    		}
    		}
    		if(unlink(UPLOAD_BASE_PATH . $fileName)){
    			Output::instance()->resultCode(code_success,"图片删除成功");
    		}else{
    			Output::instance()->resultCode(code_delete_pic);
    		}
    	}
    }
    /**
     * [uploadToOss 下载微信图片到本地以后上传到oss]
     * @return [type] [description]
     */
    public function uploadToOss($mediaId){
        $filepath=WeixinApi::downloadMedia($mediaId);
        $option = array(
            ALIOSS::OSS_HEADERS => array(
                'Content-Type' => 'image/jpg'
            ),
        );
        $extension = '.jpg';
        $filename =date('Ymd') . '/upload/' . $mediaId . $extension;
        $response = $this->oss->upload_file_by_file($this->bucket,$filename,$filepath,$option);
        if($response->status==200){
            $imageInfo=getimagesize($filepath);
            $out=new StdClass();
            $out->code=0;
            $out->path=OSSURL . $filename;
            $out->fileName=$filename;
            $out->width=$imageInfo[0];
            $out->height=$imageInfo[1];
            if (file_exists($filepath)) {
                @unlink ($filepath);
            }
            Output::instance()->object($out);
        } else {
            Output::instance()->resultCode(1,"上传失败!");
        }
    }
	/**
	 * [uploadToOss 下载微信语音到本地以后上传到oss]
	 * @return [type] [description]
	 */
	public function uploadWxVoiceToOss($mediaId){
		$cid = Session::$user['customerId'];
		$filepath=WeixinApi::downloadMedia($mediaId,'.amr');
		$newFilePath = LOCAL_PIC_PATH . md5 ( $mediaId ) . '.mp3';
		shell_exec("/usr/local/bin/ffmpeg -i $filepath $newFilePath");
		@unlink ($filepath);
		$filename =date('Ymd') . '/voice/'.$cid."/".time()."/" . md5 ($mediaId).".mp3";
		$filepath =$newFilePath;
		$option= null;
		$response = $this->oss->upload_file_by_file($this->bucket,$filename,$filepath,$option);
		if($response->status==200){
			$out=new StdClass();
			$out->code=0;
			$out->path=OSSURL . $filename;
			$out->fileName=$filename;
			if (file_exists($filepath)) {
				@unlink ($filepath);
			}
			Output::instance()->object($out);
		} else {
			return false;
		}
	}
	/**
	 * [uploadToOss 下载临时素材到本地以后上传到oss]
	 * @return [type] [description]
	 */
	public function uploadMediaToOss($mediaId,$filename,$type){
		$cid = Session::$user['customerId'];
		$filepath=WeixinApi::downWeixinMedia($mediaId,$filename);
		$filename =date('Ymd') . '/'.$type.'/'.$cid."/".time()."/" . $filename;
		$option= null;
		$response = $this->oss->upload_file_by_file($this->bucket,$filename,$filepath,$option);
		if($response->status==200){
			$imageInfo=getimagesize($filepath);
			$out=new StdClass();
			$out->code=0;
			$out->path=OSSURL . $filename;
			$out->fileName=$filename;
			$out->width=$imageInfo[0];
			$out->height=$imageInfo[1];
			if (file_exists($filepath)) {
				@unlink ($filepath);
			}
			return $out;
		} else {
			return false;
		}
	}
    /**
     * [uploadToOss 上传本地文件到oss]
     * @return [type] [description]
     */
    public function uploadLocalFileToOss($fname,$filePath){
        $option = array(
            ALIOSS::OSS_HEADERS => array(
                'Content-Type' => 'image/jpg'
            ),
        );
        $filename =date('Ymd') . 'upload/' . $fname;
        $response = $this->oss->upload_file_by_file($this->bucket,$filename,$filePath,$option);
        if($response->status==200){
            $out=new StdClass();
            $out->code=0;
            $out->path=OSSURL . $filename;
            $out->fileName=$filename;
            if (file_exists($filePath)) {
                @unlink ($filePath); 
            }
        } 
        return $out;
    }
	public function uploadStringToOss($content){
		$fname = 'product_video_img_'.time().'.png';
		$fileName=LOCAL_PIC_PATH . "$fname";
		$base64_string= explode(',', $content);
		$data= base64_decode($base64_string[1]);
		file_put_contents($fileName, $data);
		$out = self::uploadLocalFileToOss($fname,$fileName);
		if($out) {
			Output::instance()->object($out);
		}else{
			Output::instance()->resultCode(1,"上传失败!");
		}
	}
	public function uploadVideoToOss(){
		$fileinfo = $_FILES["file"];
		$fileName = $fileinfo['tmp_name'];
		$fname = $fileinfo['name'];
		$out = self::uploadLocalZipToOss($fname,$fileName);
		if($out) {
			Output::instance()->object($out);
		}else{
			Output::instance()->resultCode(1,"上传失败!");
		}
	}
    public function uploadLocalZipToOss($fname,$filePath){
        $option = array(
            ALIOSS::OSS_HEADERS => array(
                'Content-Type' => 'application/x-zip-compressed'
            ),
        );
        $filename =date('Ymd') . 'upload/' . $fname;
        $response = $this->oss->upload_file_by_file($this->bucket,$filename,$filePath,$option);
        if($response->status==200){
            $out=new StdClass();
            $out->code=0;
            $out->path=OSSURL . $filename;
            $out->fileName=$filename;
            if (file_exists($filePath)) {
                @unlink ($filePath);
            }
        }
        return $out;
    }
    public static function uploadImageToWeixin() {
        $fileInfo=$_POST;
        if(!$fileInfo) {
            echo "文件不存在！";
            return;
        }
        $result=WeixinApi::uploadImage($fileInfo);

        echo $result;
    }
}